﻿using System;
using System.Configuration;
using System.Globalization;

namespace Sustainalytics.Utils.Configuration
{
    public static class SettingsHelper
    {

        public static T Read<T>(string name, T defaultValue = default(T), bool suppressExceptions = true)  where T: IConvertible
        {
            var retValue = (T)defaultValue;
            var value = ConfigurationManager.AppSettings[name];
            if (!string.IsNullOrEmpty(value))
            {
                try
                {                    
                    retValue = (T) Convert.ChangeType(value, typeof (T), CultureInfo.InvariantCulture);
                }
                catch (Exception)
                {
                    if (!suppressExceptions)
                        throw;
                }
            }
            return retValue;
        }

        public static T ReadEnum<T>(string name, T defaultValue = default(T), bool suppressExceptions = true) where T : struct 
        {
            if (!typeof(T).IsEnum)
                throw new InvalidCastException("Type given must be an Enum");

            var retValue = (T)defaultValue;
            var value = ConfigurationManager.AppSettings[name];
            if (!string.IsNullOrEmpty(value))
            {
                try
                {
                    retValue = (T)Enum.Parse(typeof(T), value, true);
                }
                catch (Exception)
                {
                    if (!suppressExceptions)
                        throw;
                }
            }
            return retValue;
        }

  

    }
}
